package com.luzhikun.servlet.witePower;

import com.google.gson.Gson;
import com.luzhikun.domain.User;
import com.luzhikun.service.IUserService;
import com.luzhikun.service.impl.IUserServiceImpl;
import com.luzhikun.util.ServiceFactory;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(name = "IndexServlet",value = "/indexServlet")
public class IndexAjaxServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        // 获取前端传来的数据
        String phone=request.getParameter("index-phone");
        System.out.println(phone);
        // 发送异步请求到后端
        IUserService iUserService=null;
        String msg="";
        String json="{}";
        if (phone!=null && phone.trim().length()>0){
            // 创建代理类对象
            iUserService = (IUserService) ServiceFactory.getService(new IUserServiceImpl());
            User user = iUserService.useerIndexSerlectByPhone(phone);
            if (user!=null){

                msg="电话号码已被使用";
                Gson gson=new Gson();
                json = gson.toJson(msg);
//                json="{\"msg\":msg}";
//                System.out.println(json);
            }else {
                msg="该号码可以使用";
                Gson gson=new Gson();
                json = gson.toJson(msg);
                System.out.println(json);
            }
            // 把获取的数组通过网络传给ajax中的异步对象，响应结果数据
            response.setContentType("application/json;charset=UTF-8");
            PrintWriter printWriter=response.getWriter();
            printWriter.println(json);
            printWriter.flush();
            printWriter.close();

        }

//        String username = request.getParameter("index-username");
//        String password = request.getParameter("index-password");
//        System.out.println(username);
//        System.out.println(password);
//        // 用户注册
//        iUserService.userIndex(username, password);

    }
}
